//
//  NetworkTool.m
//  WANTS购物
//
//  Created by xuNick on 16/5/28.
//  Copyright © 2016年 NN. All rights reserved.
//

#import "NetworkTool.h"
#import <Reachability.h>

@protocol NetworkToolsProxy <NSObject>

@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end

@interface NetworkTool ()<NetworkToolsProxy>

@end


@implementation NetworkTool

+(instancetype)shareNetworkTool{
    
        static NetworkTool *instance;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
            instance = [[self alloc]initWithSessionConfiguration:config];
            
            //返回类型
            instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
            
            //请求格式  非常重要。 没有请求的code为1
            instance.requestSerializer = [AFJSONRequestSerializer serializer];
            
            //5.超时
            instance.requestSerializer.timeoutInterval = 10.0;
        });
        return instance;
    

}

-(void)request:(RequestMethod)method urlString:(NSString *)urlString parameters:(id)parameters finished:(void (^)(id, NSError *))finished{
    NSString *reqMethod = (method == RequestMethodGet) ? @"get" : @"post";
    [[self dataTaskWithHTTPMethod:@"get" URLString:urlString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask * dataTask, id responseObject) {
        NSLog(@"下载完成");
        finished(responseObject,nil);
    } failure:^(NSURLSessionDataTask * dataTask, NSError * error) {
        finished(error,nil);
    }] resume];
}

-(BOOL)isReachableByAFN{
    Reachability *reachability = [Reachability reachabilityWithHostName:@"http://iosapi.itcast.cn"];
    //如果能成功连接则会是ture
    return reachability.isReachable;
}








@end
